package com.vca.service.util;


import cn.hutool.core.date.DateUtil;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.HeaderResponse;
import com.vca.common.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * @Description:华为云OBS工具类
 * @author:chenbing
 * @date 2023/6/12 18:19
 */
@Component
public class OBSUtils {

    public static final Logger logger = LoggerFactory.getLogger(OBSUtils.class);

    /**
     * @Description:上传对象
     * @author:chenbing
     * @date 2023/6/12 18:19
     */
    public static void uploadObject(String nameDir, String endPoint, String accessKey, String secretKey, String bucketName, File file, String table) {
        ObsClient obsClient = null;
        try {
            // 创建ObsClient实例
            obsClient = new ObsClient(accessKey, secretKey, endPoint);
            //调用PutObject上传接口，进行上传对象
            String name = file.getName();
            String objectKey = name;
            String key = nameDir + "/" + table + "/etl_date=";
            if (name.contains("vca_order") || name.contains("vca_order_info")) {
//                String etlDate = DateUtil.format(DateUtil.yesterday(), Constants.DATE_FORMAT_NUM);
                String etlDate = DateUtil.format(DateUtil.date(), Constants.DATE_FORMAT_NUM);
                objectKey = key + etlDate + "/" + name;
            } else {
                String etlDate = DateUtil.format(DateUtil.date(), Constants.DATE_FORMAT_NUM);
                objectKey = key + etlDate + "/" + name;
            }
            HeaderResponse response = obsClient.putObject(bucketName, objectKey, file);
            logger.info("response===>{}", response);

        } catch (ObsException e) {
            e.printStackTrace();
            logger.error("HTTP Code: " + e.getResponseCode());
            logger.error("Error Code:" + e.getErrorCode());
            logger.error("Error Message: " + e.getErrorMessage());

            logger.error("Request ID:" + e.getErrorRequestId());
            logger.error("Host ID:" + e.getErrorHostId());
            logger.error("OBS上传文件失败");
        } finally {
            // 关闭ObsClient实例，如果是全局ObsClient实例，可以不在每个方法调用完成后关闭
            // ObsClient在调用ObsClient.close方法关闭后不能再次使用
            if (obsClient != null) {
                try {
                    obsClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
